package com.heima.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.Mapper.AdminAdUserMapper;
import com.heima.model.Admin.Pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdminLoginService implements com.heima.Service.AdminLoginService {
    @Autowired
    AdminAdUserMapper adminAdUserMapper;
//    登录接口
    @Override
    public ResponseResult Login(AdUser adUser) {
//        查询用户是否存在
        AdUser user=ExistUser(adUser);
//        存在
        if(user!=null)
        {
            //        判断密码是否正确
            if(!(user.getPassword().equals(MD5Utils.encodeWithSalt(adUser.getPassword(),user.getSalt()))))
            {
                //        不正确
                return ResponseResult.errorResult(403,"密码错误");
            }

                //        正确
            Map<String,Object> arr=new HashMap<>();
            arr.put("token", AppJwtUtil.getToken(user.getId().longValue()));
            user.setPassword("");
            arr.put("user",user);
            return ResponseResult.okResult(arr);
        }
        //        不存在
        else
        {
            return ResponseResult.errorResult(404,"用户不存在");
        }
    }

    private AdUser ExistUser(AdUser adUser)
    {
        AdUser user=new AdUser();
        try{
            QueryWrapper<AdUser> wrapper=new QueryWrapper<>();
            wrapper.eq("name",adUser.getName());
            user = adminAdUserMapper.selectOne(wrapper);
        }
        catch (Exception e)
        {
            log.error("查询用户出错");
            e.printStackTrace();
        }
        return user;
    }
}
